package com.sky.controller.admin;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDto;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.exception.PasswordEditFailedException;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/admin/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO loginDTO) {
        EmployeeLoginVO loginVO = employeeService.login(loginDTO);
        return Result.success(loginVO);
    }

    //登出功能
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        // 1. 从请求头中获取token
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        redisTemplate.delete("admin_token:" + token);
        return Result.success();
    }

    //修改员工密码
    @PutMapping("/editPassword")
    public Result updatePass(HttpServletRequest request, @RequestBody EmployeeDto employeeDto) {


        String token = request.getHeader(jwtProperties.getAdminTokenName());
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(),token);
        Long eId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
        log.info("当前员工id：{}", eId);

        employeeDto.setEmpId(eId);

        try {
            //md5加密员工密码
            String md5newps = DigestUtils.md5DigestAsHex(employeeDto.getNewPassword().getBytes());
            employeeDto.setNewPassword(md5newps);

            String md5oldps = DigestUtils.md5DigestAsHex(employeeDto.getOldPassword().getBytes());
            employeeDto.setOldPassword(md5oldps);

            employeeService.updatePass(employeeDto);
        } catch (PasswordEditFailedException e) {
            e.printStackTrace();
        }

        return Result.success();
    }


    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("启用禁用员工账号")
    public Result startOrStop(@PathVariable Integer status,Long id){
        log.info("启用禁用员工账号：{},{}",status,id);
        employeeService.startOrStop(status,id);//后绪步骤定义
        return Result.success();
    }

    //员工分页查询
    @GetMapping("/page")
    public Result<PageResult> page(String name, int page, int pageSize) {

        log.info("分页查询，参数：{},{},{}", page, pageSize, name);

        PageResult pageinfo = employeeService.page(page, pageSize, name);

        if(pageinfo.getTotal()>0){
            return Result.success(pageinfo);
        }else {
            return Result.error("未找到相关员工");
        }
    }

    //新增员工
    @PostMapping
    public Result save(@RequestBody Employee employee) {
        log.info("新增员工：{}", employee.toString());

        //密码常量 PasswordConstant.DEFAULT_PASSWORD
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        employeeService.save(employee);
        return Result.success();
    }

    //根据id查询员工
    @GetMapping("/{id}")
    public Result<Employee> selecById(@PathVariable Long id) {

        Employee emp = employeeService.selecById(id);

        if (emp != null) {
            return Result.success(emp);
        }
        return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);//账户不存在

    }

    //编辑员工信息
    @PutMapping
    public Result updateEmp(@RequestBody Employee employee) {
        log.info("修改员工信息{}",employee.toString());

        Integer it = employeeService.updateEmp(employee);

        if(it != null){
            return Result.success();
        }

        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }



}
